package com.nuc.thread.cas.automicrefrence;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicStampedReference;
import java.util.function.Supplier;

/**
 * @author 诗酒趁年华
 * @version 1.0.0
 * @Description AtomicStampedReference加了版本号
 * @createTime 2021年07月12日 12:59:00
 */
@Slf4j
public class Test2 {
    private static AtomicStampedReference<String> reference = new AtomicStampedReference<>("A",0);
    public static void main(String[] args) throws InterruptedException {
        String prev = reference.getReference();
        int stamp = reference.getStamp();//版本号
        other();//主线程并不知道其他线程曾经修改过共享变量的值
        Thread.sleep(1000);//休眠一秒
        log.debug("主线程拿到的版本号为:{}",stamp);
        log.debug("主线程修改的结果为：{}",reference.compareAndSet(prev,"C",stamp,stamp+1));
        log.debug("当前共享变量中的值为:{}",reference.getReference());



    }

    static void other() throws InterruptedException {
        new Thread(()->{
            String prev = reference.getReference();
            int stamp = reference.getStamp();//版本号
            log.debug("修改结果 A->B,版本号为:{}",stamp);
            reference.compareAndSet(prev,"B",stamp,stamp+1);
        },"t1").start();

        Thread.sleep(500);
        new Thread(()->{
            String prev = reference.getReference();
            int stamp = reference.getStamp();//版本号
            log.debug("修改结果 B->A,版本号为{}",stamp);
            reference.compareAndSet(prev,"A",stamp,stamp+1);
        },"t2").start();

    }

}
